import { ref, reactive } from 'vue'
import { defineStore } from 'pinia'
import { getSocket } from '../utils/mysocket'

const ws = getSocket()

export const useWsuserStore = defineStore('wsuser', () => {
  const account = reactive({
    id: 0,
    name: 'world',
    role: ''
  })
  const userinfo = ref({})

  //使用Promise包裹axios对象，更换resolve的参数
  const login = (params) => {
    return new Promise((resolve) => {
      ws.sending('login', params).then(
        (res) => {
          if (res.info.status == 201) {
            account.id = res.data.id
            account.name = res.data.name
            account.role = res.data.role
          }
          resolve(res)
        },
        (reason) => {
          console.log(reason)
        }
      )
    })
  }
  //使用callback，替代resolve及参数
  const regist = (callback) => {
    let promise = ws.sending('regist', userinfo.value)
    promise.then((res) => {
      console.log(res.info.msg)
      callback(res.info.status == 201)
    })
    return promise
  }

  const test = (par) => {
    ws.sending('test', par)
  }
  const unlink = () => {
    ws.closing()
  }

  return { login, regist, userinfo, account, test, unlink }
})
